package net.jiastudy.biz.project.service.impl;

import net.jiastudy.biz.project.mapper.PersonalProjectCategoryMapper;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;

import cn.hutool.core.util.StrUtil;
import net.jiastudy.biz.project.entity.PersonalProjectCategory;
import net.jiastudy.biz.project.service.PersonalProjectCategoryService;
import net.jiastudy.core.base.BaseService;
import net.jiastudy.core.exception.ServiceException;

@Service
@Transactional(rollbackFor = Exception.class)
public class PersonalProjectCategoryServiceImpl extends BaseService<PersonalProjectCategoryMapper, PersonalProjectCategory> implements PersonalProjectCategoryService {

	@Override
	public PersonalProjectCategory createCategory(PersonalProjectCategory category) {
		if (this.checkCodeExists(category.getCode(), null)) {
			throw new ServiceException("category.code.exists", "code已经存在");
		}
		if (this.insert(category)) {
			return category;
		}
		return null;
	}

	@Override
	public boolean deleteCategory(Long id) {
		return this.deleteById(id);
	}

	@Override
	public PersonalProjectCategory updateCategory(PersonalProjectCategory category) {
		if (this.checkCodeExists(category.getCode(), category.getId())) {
			throw new ServiceException("category.code.exists", "code已经存在");
		}
		if (this.updateById(category)) {
			return category;
		}
		return null;
	}

	@Override
	public List<PersonalProjectCategory> findCategorys(String keywords) {
		Wrapper<PersonalProjectCategory> wrapper = new EntityWrapper<>();
		if (StrUtil.isNotEmpty(keywords)) {
			wrapper.andNew().like("name", keywords).or().like("code", keywords);
		}
		return this.selectList(wrapper);
	}
	
	@Override
	public boolean checkCodeExists(String code, Long id) {
		if (null == code) {
			return false;
		}
		PersonalProjectCategory entity = new PersonalProjectCategory();
		entity.setCode(code);
		PersonalProjectCategory category = baseMapper.selectOne(entity);
		if (null == category) {
			return false;
		}
		if (category.getId().equals(id)) {
			return false;
		}
		return true;
	}

}
